// 导入新的 API 方法
import {
  getAllProjectsService,
  getProjectsBySchoolService,
  getSchoolByIdService,
  searchProjectsService,
  increaseProjectReadCountService
} from "../../api/project";

Page({
  data: {
    currentTab: "all",
    currentFilter: "award",
    allProjectList: [],
    mySchoolProjectList: [],
    
    // 新增：搜索相关数据
    searchProjectList: [],
    searchKeyword: "",
    searchPageInfo: {
      pageNum: 1,
      pageSize: 5,
      hasMore: true,
      loading: false,
      total: 0
    },
    showSearchResults: false,

    // 分页相关数据
    allPageInfo: {
      pageNum: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      reachedEnd: false,
    },
    mySchoolPageInfo: {
      pageNum: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      reachedEnd: false,
    },

    // 用户学校信息
    userSchool: "",
    userSchoolId: null,

    // 学校信息缓存
    schoolInfoCache: {},
    allScrollTop: 0,
    mySchoolScrollTop: 0,
  },

  // ==================== 工具方法 ====================

  /**
   * 获取认证头
   */
  getAuthHeader() {
    const token = wx.getStorageSync("token");

    if (token) {
      return {
        "content-type": "application/json",
        Authorization: token,
      };
    } else {
      this.checkLoginStatus();
      return {
        "content-type": "application/json",
      };
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    if (!token) {
      return false;
    }
    return true;
  },

  /**
   * 截取项目简要信息（最多40个字符）
   */
  truncateProjectInfo(projectInfo) {
    if (!projectInfo) return "";
    return projectInfo.length > 40
      ? projectInfo.substring(0, 40) + "..."
      : projectInfo;
  },

  // ==================== 学校信息相关方法 ====================

  async getSchoolInfoById(schoolId) {
    if (!schoolId && schoolId !== 0) return { schoolname: "未知学校" };

    const id = parseInt(schoolId);

    // 检查缓存
    if (this.data.schoolInfoCache[id]) {
      return this.data.schoolInfoCache[id];
    }

    // 如果缓存中没有，从API获取
    try {
      const res = await getSchoolByIdService(id);
      console.log(`获取学校${id}信息响应:`, res);

      if (res && res.code === 200) {
        const schoolInfo = res.data;

        // 缓存学校信息
        const updatedCache = {
          ...this.data.schoolInfoCache,
          [id]: schoolInfo,
        };

        this.setData({
          schoolInfoCache: updatedCache,
        });

        return schoolInfo;
      } else {
        const fallbackInfo = {
          id: id,
          schoolname: "登录/注册后查看学校",
          home: "未知",
          code: "",
        };

        const updatedCache = {
          ...this.data.schoolInfoCache,
          [id]: fallbackInfo,
        };

        this.setData({
          schoolInfoCache: updatedCache,
        });

        return fallbackInfo;
      }
    } catch (err) {
      console.error("获取学校信息失败:", err);
      const fallbackInfo = {
        id: id,
        schoolname: "登录/注册后查看学校",
        home: "未知",
        code: "",
      };
      return fallbackInfo;
    }
  },

  getSchoolNameById(schoolId) {
    if (!schoolId && schoolId !== 0) return "未知学校";

    const id = parseInt(schoolId);
    if (this.data.schoolInfoCache[id]) {
      return this.data.schoolInfoCache[id].schoolname;
    }
    return "登录/注册后查看学校";
  },

  async batchGetSchoolInfo(schoolIds) {
    const uniqueIds = [...new Set(schoolIds)].filter(
      (id) => id !== null && id !== undefined,
    );
    const promises = uniqueIds.map((id) => this.getSchoolInfoById(id));

    try {
      await Promise.all(promises);
    } catch (err) {
      console.error("批量获取学校信息失败:", err);
    }
  },

  getUserSchool() {
    return new Promise((resolve, reject) => {
      if (!this.checkLoginStatus()) {
        reject("未登录");
        return;
      }

      const userInfo = wx.getStorageSync("userInfo");

      if (userInfo && userInfo.school !== undefined && userInfo.school !== null) {
        const schoolId = parseInt(userInfo.school);
        const schoolName = userInfo.schoolname || this.getSchoolNameById(schoolId);

        this.setData({
          userSchoolId: schoolId,
          userSchool: schoolName,
        });

        wx.setStorageSync("userSchoolId", schoolId);
        wx.setStorageSync("userSchool", schoolName);

        resolve({ schoolId, schoolName });
      } else {
        wx.request({
          url: "https://kuaizu.xyz/user/school",
          method: "GET",
          header: this.getAuthHeader(),
          success: async (res) => {
            if (res.statusCode === 200 && res.data) {
              let schoolId = null;
              let schoolName = "";

              if (
                res.data.data &&
                Array.isArray(res.data.data) &&
                res.data.data.length > 0
              ) {
                const userData = res.data.data[0];
                schoolId = userData.schoolId || userData.school;
              } else if (res.data.schoolId || res.data.school) {
                schoolId = res.data.schoolId || res.data.school;
              } else if (res.data.data && res.data.data.schoolId) {
                schoolId = res.data.data.schoolId || res.data.data.school;
              }

              if (schoolId !== null && schoolId !== undefined) {
                schoolId = parseInt(schoolId);

                try {
                  const schoolInfo = await this.getSchoolInfoById(schoolId);
                  schoolName = schoolInfo.schoolname;

                  this.setData({
                    userSchoolId: schoolId,
                    userSchool: schoolName,
                  });

                  wx.setStorageSync("userSchoolId", schoolId);
                  wx.setStorageSync("userSchool", schoolName);

                  resolve({ schoolId, schoolName });
                } catch (err) {
                  schoolName = this.getSchoolNameById(schoolId);

                  this.setData({
                    userSchoolId: schoolId,
                    userSchool: schoolName,
                  });

                  resolve({ schoolId, schoolName });
                }
              } else {
                const defaultSchoolId = 1;
                const defaultSchoolName = "某某大学";

                this.setData({
                  userSchoolId: defaultSchoolId,
                  userSchool: defaultSchoolName,
                });

                resolve({
                  schoolId: defaultSchoolId,
                  schoolName: defaultSchoolName,
                });
              }
            } else if (res.statusCode === 401) {
              this.handleAuthError();
              reject("认证失败");
            } else {
              reject("获取学校信息失败");
            }
          },
          fail: (err) => {
            reject("网络请求失败");
          },
        });
      }
    });
  },

  // ==================== 数据格式化方法 ====================

  getEducationText(educationRequirement) {
    if (!educationRequirement) return "不限";

    let educationArray = [];
    if (typeof educationRequirement === "string") {
      try {
        educationArray = JSON.parse(educationRequirement);
      } catch (e) {
        educationArray = educationRequirement
          .split(",")
          .map((item) => item.trim());
      }
    } else if (Array.isArray(educationRequirement)) {
      educationArray = educationRequirement;
    } else {
      educationArray = [educationRequirement];
    }

    const educationTexts = educationArray
      .map((education) => {
        const edu = parseInt(education);
        switch (edu) {
          case 1:
            return "大专";
          case 2:
            return "本科";
          case 3:
            return "研究生";
          default:
            return "不限";
        }
      })
      .filter((text) => text !== "不限");

    const uniqueTexts = [...new Set(educationTexts)];
    const sortOrder = ["大专", "本科", "研究生"];
    uniqueTexts.sort((a, b) => sortOrder.indexOf(a) - sortOrder.indexOf(b));

    return uniqueTexts.length > 0 ? uniqueTexts.join("/") : "不限";
  },

  getDirectionText(direction) {
    const dir = parseInt(direction);
    switch (dir) {
      case 1:
        return "落地";
      case 2:
        return "获奖";
      case 3:
        return "学习";
      default:
        return "其他";
    }
  },

  getCrossSchoolText(crossSchool) {
    const cross = parseInt(crossSchool);
    switch (cross) {
      case 1:
        return "接受跨校";
      case 0:
        return "仅接受本校";
      default:
        return "仅接受本校";
    }
  },

  // ==================== 搜索相关方法 ====================

  /**
   * 处理搜索输入
   */
  onSearchInput(e) {
    const value = e.detail.value;
    this.setData({
      searchKeyword: value
    });
  },

  /**
   * 执行搜索
   */
  onSearch() {
    const keyword = this.data.searchKeyword.trim();
    
    if (!keyword) {
      wx.showToast({
        title: "请输入搜索内容",
        icon: "none",
        duration: 2000
      });
      return;
    }

    // 重置搜索状态
    this.setData({
      searchProjectList: [],
      "searchPageInfo.pageNum": 1,
      "searchPageInfo.hasMore": true,
      showSearchResults: true
    });

    this.performSearch(true);
  },

  /**
   * 执行搜索请求
   */
  performSearch(refresh = false) {
    const pageInfo = this.data.searchPageInfo;
    
    if (pageInfo.loading || (!refresh && !pageInfo.hasMore)) {
      return;
    }

    if (refresh) {
      this.setData({
        "searchPageInfo.pageNum": 1,
        "searchPageInfo.hasMore": true,
      });
    }

    this.setData({
      "searchPageInfo.loading": true,
    });

    const currentPageNum = refresh ? 1 : this.data.searchPageInfo.pageNum;

    const requestData = {
      str: this.data.searchKeyword,
      pageNum: currentPageNum,
      pageSize: this.data.searchPageInfo.pageSize
    };

    searchProjectsService(requestData)
      .then((res) => {
        if (res && res.code === 200) {
          const responseData = res.data;
          const rawProjects = responseData.data || [];
          const total = responseData.total || 0;

          // 格式化搜索结果，直接使用接口返回的顺序
          const formattedProjects = rawProjects.map((project) => {
            return {
              ...project,
              educationText: this.getEducationText(project.educationRequirement),
              directionText: this.getDirectionText(project.direction),
              crossSchoolText: this.getCrossSchoolText(project.crossSchool),
              schoolDisplay: project.schoolName || "未知学校",
              skillRequirement: this.getCrossSchoolText(project.crossSchool),
              projectInfo: this.truncateProjectInfo(project.projectInfo),
            };
          });

          let updatedList;
          if (refresh) {
            updatedList = formattedProjects;
          } else {
            updatedList = [...this.data.searchProjectList, ...formattedProjects];
          }

          const hasMore = currentPageNum < Math.ceil(total / this.data.searchPageInfo.pageSize);

          this.setData({
            searchProjectList: updatedList,
            "searchPageInfo.pageNum": currentPageNum + 1,
            "searchPageInfo.hasMore": hasMore,
            "searchPageInfo.total": total
          });

          setTimeout(() => {
            this.setData({
              "searchPageInfo.loading": false,
            });
          }, 500);
        } else {
          this.handleLoadError("搜索失败");
        }
      })
      .catch((err) => {
        this.handleLoadError("网络错误，请重试");
      });
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({
      searchKeyword: "",
      searchProjectList: [],
      showSearchResults: false,
      "searchPageInfo.pageNum": 1,
      "searchPageInfo.hasMore": true,
      "searchPageInfo.total": 0
    });
  },

  // ==================== 事件处理方法 ====================

  /**
   * 切换筛选标签
   */
  switchFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    
    if (this.data.currentFilter === filter) {
      return;
    }
    
    // 更新筛选状态
    this.setData({
      currentFilter: filter,
    });

    // 重新加载数据
    if (this.data.currentTab === "all") {
      this.setData({
        allProjectList: [],
        "allPageInfo.pageNum": 1,
        "allPageInfo.hasMore": true,
      });
      this.loadAllProjects(true);
    } else if (this.data.currentTab === "mySchool") {
      this.setData({
        mySchoolProjectList: [],
        "mySchoolPageInfo.pageNum": 1, 
        "mySchoolPageInfo.hasMore": true,
      });
      this.loadMySchoolProjects(true);
    }
  },

  /**
   * 切换标签页
   */
  switchTab(e) {
    const currentTab = e.currentTarget.dataset.tab;
    
    this.setData({
      currentTab: currentTab,
    });

    // 如果切换到搜索页面，清空之前的搜索结果
    if (currentTab === "search") {
      this.clearSearch();
    }

    setTimeout(() => {
      if (currentTab !== "search") {
        wx.pageScrollTo({
          scrollTop: currentTab === 'all' ? this.data.allScrollTop : this.data.mySchoolScrollTop,
          duration: 0
        });
      }
    }, 0);

    if (currentTab === "all" && this.data.allProjectList.length === 0) {
      this.loadAllProjects(true);
    } else if (
      currentTab === "mySchool" &&
      this.data.mySchoolProjectList.length === 0
    ) {
      if (!this.checkLoginStatus()) {
        wx.showModal({
          title: "提示",
          content: "查看本校项目需要先登录",
          showCancel: true,
          cancelText: "取消",
          confirmText: "去登录",
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: "/pages/login/login",
              });
            } else {
              this.setData({
                currentTab: "all",
              });
            }
          },
        });
        return;
      }
      
      if (!this.data.userSchoolId && this.data.userSchoolId !== 0) {
        this.getUserSchool()
          .then(() => {
            this.loadMySchoolProjects(true);
          })
          .catch((err) => {
            wx.showToast({
              title: "获取学校信息失败",
              icon: "error",
              duration: 2000,
            });
          });
      } else {
        this.loadMySchoolProjects(true);
      }
    }
  },

  projectDetails(e) {
    const projectId = e.currentTarget.dataset.projectId;

    if (!projectId) {
      wx.showToast({
        title: "项目信息错误",
        icon: "error",
        duration: 2000,
      });
      return;
    }

    this.increaseReadCount(projectId);

    wx.navigateTo({
      url: `/pages/projectDetails/projectDetails?projectId=${projectId}`,
    });
  },

  // ==================== 数据处理方法 ====================

  increaseReadCount(projectId) {
    const token = wx.getStorageSync("token");

    if (!token || !projectId) {
      return;
    }

    increaseProjectReadCountService(projectId)
      .then((res) => {
        this.updateLocalReadCount(projectId);
      })
      .catch((err) => {
        console.error(`增加项目${projectId}阅读量失败：`, err);
      });
  },

  updateLocalReadCount(projectId) {
    const updatedAllProjects = this.data.allProjectList.map((project) => {
      if (project.id === projectId) {
        return {
          ...project,
          readCount: (project.readCount || 0) + 1,
          lookcount: (project.lookcount || 0) + 1,
        };
      }
      return project;
    });

    const updatedMySchoolProjects = this.data.mySchoolProjectList.map(
      (project) => {
        if (project.id === projectId) {
          return {
            ...project,
            readCount: (project.readCount || 0) + 1,
            lookcount: (project.lookcount || 0) + 1,
          };
        }
        return project;
      },
    );

    const updatedSearchProjects = this.data.searchProjectList.map(
      (project) => {
        if (project.id === projectId) {
          return {
            ...project,
            readCount: (project.readCount || 0) + 1,
            lookcount: (project.lookcount || 0) + 1,
          };
        }
        return project;
      },
    );

    this.setData({
      allProjectList: updatedAllProjects,
      mySchoolProjectList: updatedMySchoolProjects,
      searchProjectList: updatedSearchProjects
    });
  },

  // ==================== 数据加载方法 ====================

  /**
   * 加载所有学校的项目
   */
  async loadAllProjects(refresh = false) {
    const pageInfo = this.data.allPageInfo;
    
    if (pageInfo.loading || (!refresh && !pageInfo.hasMore)) {
      return;
    }
    
    if (refresh) {
      pageInfo.pageNum = 1;
      pageInfo.hasMore = true;
      pageInfo.reachedEnd = false;
    }

    this.setData({
      "allPageInfo.loading": true,
    });

    // 根据筛选条件设置项目偏向
    let status;
    switch (this.data.currentFilter) {
      case "landing":
        status = 1;
        break;
      case "award":
        status = 2;
        break;
      case "learning":
        status = 3;
        break;
      default:
        status = 2;
    }

    const requestData = {
      pageNum: pageInfo.pageNum.toString(),
      pageSize: pageInfo.pageSize.toString(),
      status: status.toString(), // 传递项目偏向参数
    };

    console.log('请求所有项目参数:', requestData);

    getAllProjectsService(requestData)
      .then((res) => {
        if (res) {
          const responseData = res.data || res;
          const rawProjects = responseData.items || [];

          console.log('接口返回项目数据:', rawProjects.slice(0, 3).map(p => ({
            id: p.id,
            projectName: p.projectName,
            applicationCount: p.applicationCount,
            direction: p.direction,
            lookcount: p.lookcount
          })));

          // 格式化数据，直接使用接口返回的顺序（已按投递量排序）
          const formattedProjects = rawProjects.map((project) => {
            return {
              ...project,
              educationText: this.getEducationText(project.educationRequirement),
              directionText: this.getDirectionText(project.direction),
              crossSchoolText: this.getCrossSchoolText(project.crossSchool),
              schoolDisplay: project.schoolname || "未知学校",
              skillRequirement: this.getCrossSchoolText(project.crossSchool),
              projectInfo: this.truncateProjectInfo(project.projectInfo),
            };
          });
          
          // 更新数据
          const total = responseData.total || 0;
          const currentPage = pageInfo.pageNum;
          const totalPages = Math.ceil(total / pageInfo.pageSize);

          let updatedList;
          if (refresh) {
            updatedList = formattedProjects;
          } else {
            updatedList = [...this.data.allProjectList, ...formattedProjects];
          }

          const hasMore = currentPage < totalPages;

          this.setData({
            allProjectList: updatedList,
            "allPageInfo.pageNum": currentPage + 1,
            "allPageInfo.hasMore": hasMore,
          });

          setTimeout(() => {
            this.setData({
              "allPageInfo.loading": false,
            });
          }, 500);
        } else {
          this.handleLoadError("加载项目失败");
        }
      })
      .catch((err) => {
        console.error('加载项目失败:', err);
        this.handleLoadError("网络错误，请重试");
      });
  },

  /**
   * 加载本校项目
   */
  loadMySchoolProjects(refresh = false) {
    const pageInfo = this.data.mySchoolPageInfo;

    if (!this.checkLoginStatus()) {
      return;
    }

    if (pageInfo.loading || (!refresh && !pageInfo.hasMore)) {
      return;
    }

    if (!this.data.userSchoolId && this.data.userSchoolId !== 0) {
      this.getUserSchool()
        .then(() => {
          this.loadMySchoolProjects(refresh);
        })
        .catch((err) => {
          this.handleLoadError("获取用户学校信息失败");
        });
      return;
    }

    if (refresh) {
      pageInfo.pageNum = 1;
      pageInfo.hasMore = true;
      pageInfo.reachedEnd = false;
    }

    this.setData({
      "mySchoolPageInfo.loading": true,
    });

    // 根据筛选条件设置项目偏向
    let status;
    switch (this.data.currentFilter) {
      case "landing":
        status = 1;
        break;
      case "award":
        status = 2;
        break;
      case "learning":
        status = 3;
        break;
      default:
        status = 2;
    }

    const requestData = {
      pageNum: pageInfo.pageNum.toString(),
      pageSize: pageInfo.pageSize.toString(),
      school: this.data.userSchoolId.toString(),
      status: status.toString(), // 传递项目偏向参数
    };

    console.log('请求本校项目参数:', requestData);

    getProjectsBySchoolService(requestData)
      .then((res) => {
        if (res) {
          const responseData = res.data || res;
          const rawProjects = responseData.items || [];

          console.log('接口返回本校项目数据:', rawProjects.slice(0, 3).map(p => ({
            id: p.id,
            projectName: p.projectName,
            deliveryCount: p.deliveryCount || p.deliverycount,
            direction: p.direction
          })));

          // 格式化数据，直接使用接口返回的顺序（已按投递量排序）
          const formattedProjects = rawProjects.map((project) => {
            return {
              ...project,
              educationText: this.getEducationText(project.educationRequirement),
              directionText: this.getDirectionText(project.direction),
              crossSchoolText: this.getCrossSchoolText(project.crossSchool),
              schoolDisplay: project.schoolname || "未知学校",
              skillRequirement: this.getCrossSchoolText(project.crossSchool),
              projectInfo: this.truncateProjectInfo(project.projectInfo),
            };
          });
          
          // 更新数据
          const total = responseData.total || 0;
          const currentPage = res.data.pageNum || pageInfo.pageNum;
          const totalPages = Math.ceil(total / pageInfo.pageSize);

          let updatedList;
          if (refresh) {
            updatedList = formattedProjects;
          } else {
            updatedList = [...this.data.mySchoolProjectList, ...formattedProjects];
          }

          this.setData({
            mySchoolProjectList: updatedList,
            "mySchoolPageInfo.pageNum": currentPage + 1,
            "mySchoolPageInfo.hasMore": currentPage < totalPages,
          });

          setTimeout(() => {
            this.setData({
              "mySchoolPageInfo.loading": false,
            });
          }, 500);
        } else {
          this.handleLoadError("加载本校项目失败");
        }
      })
      .catch((err) => {
        console.error('加载本校项目失败:', err);
        this.handleLoadError("网络错误，请重试");
      });
  },

  // ==================== 错误处理方法 ====================

  handleAuthError() {
    this.setData({
      "allPageInfo.loading": false,
      "mySchoolPageInfo.loading": false,
      "searchPageInfo.loading": false,
    });

    wx.removeStorageSync("token");

    wx.showModal({
      title: "认证失败",
      content: "登录已过期，请重新登录",
      showCancel: false,
      confirmText: "确定",
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: "/pages/login/login",
          });
        }
      },
    });
  },

  handleLoadError(message) {
    this.setData({
      "allPageInfo.loading": false,
      "mySchoolPageInfo.loading": false,
      "searchPageInfo.loading": false,
    });

    wx.showToast({
      title: message,
      icon: "error",
      duration: 2000,
    });
  },

  // ==================== 生命周期方法 ====================

  onLoad(options) {
    this.loadAllProjects(true);

    if (this.checkLoginStatus()) {
      this.getUserSchool()
        .then((schoolInfo) => {
          // 用户学校信息获取成功
        })
        .catch((err) => {
          // 获取用户学校信息失败
        });
    }
  },

  onShow() {
    if (this.data.allProjectList.length === 0) {
      this.loadAllProjects(true);
    }
    
    if (this.checkLoginStatus() && this.data.mySchoolProjectList.length === 0) {
      this.getUserSchool()
        .then(() => {
          this.loadMySchoolProjects(true);
        })
        .catch(() => {
          // 获取用户学校信息失败
        });
    }
  },

  onReachBottom() {
    if (this.data.allPageInfo.loading || this.data.mySchoolPageInfo.loading || this.data.searchPageInfo.loading) {
      return;
    }
    
    if (this.data.currentTab === "all") {
      if (this.data.allPageInfo.hasMore) {
        this.loadAllProjects(false);
      } else {
        if (!this.data.allPageInfo.reachedEnd) {
          this.setData({
            "allPageInfo.reachedEnd": true,
          });
          wx.showToast({
            title: "已加载全部内容",
            icon: "none",
            duration: 1500,
          });
        }
      }
    } else if (this.data.currentTab === "mySchool") {
      if (this.data.mySchoolPageInfo.hasMore) {
        this.loadMySchoolProjects(false);
      } else {
        if (!this.data.mySchoolPageInfo.reachedEnd) {
          this.setData({
            "mySchoolPageInfo.reachedEnd": true,
          });
          wx.showToast({
            title: "已加载全部内容",
            icon: "none",
            duration: 1500,
          });
        }
      }
    } else if (this.data.currentTab === "search") {
      if (this.data.searchPageInfo.hasMore) {
        this.performSearch(false);
      } else {
        wx.showToast({
          title: "已加载全部搜索结果",
          icon: "none",
          duration: 1500,
        });
      }
    }
  },

  onPageScroll(e) {
    if (this.data.currentTab === 'all') {
      this.data.allScrollTop = e.scrollTop;
    } else if (this.data.currentTab === 'mySchool') {
      this.data.mySchoolScrollTop = e.scrollTop;
    }
  },
});